﻿public class PIDController
{
    private double previousError;
    private double integral;

    // PID 控制参数
    private double Kp; // 比例参数
    private double Ki; // 积分参数
    private double Kd; // 微分参数

    public PIDController(double Kp, double Ki, double Kd)
    {
        this.Kp = Kp;
        this.Ki = Ki;
        this.Kd = Kd;
        this.previousError = 0;
        this.integral = 0;
    }


    /// <summary>
    /// （pid 输出的偏差 + 当前值）如果在阈值范围内，则不打开灯管，如果在阈值范围外，则打开灯管
    /// </summary>
    /// <param name="setpoint">目标值</param>
    /// <param name="processValue">过程值</param>
    /// <returns>返回偏差值</returns>
    public double Calculate(double setpoint, double processValue)
    {
        double error = setpoint - processValue;

        // 计算积分项
        integral += error;

        // 计算微分项
        double derivative = error - previousError;

        // 计算PID输出
        double output = Kp * error + Ki * integral + Kd * derivative;

        // 更新上一个误差
        previousError = error;

        return output;
    }
}
